package com.xyht.medicine_management_system.modules.common.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.medicine_management_system.common.commonReturn.CommonCodeEnum;
import com.xyht.medicine_management_system.common.commonReturn.CommonResult;
import com.xyht.medicine_management_system.common.commonReturn.ResponseResult;
import com.xyht.medicine_management_system.modules.common.entity.MmsImportTask;
import com.xyht.medicine_management_system.modules.common.mapper.MmsImportTaskMapper;
import com.xyht.medicine_management_system.modules.common.service.MmsFileUpDownService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.xyht.medicine_management_system.modules.common.constant.FileSavePathConstant.*;

/**
 * <p>
 * 批量导入任务表 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-11-30
 */
@Service
public class MmsFileUpDownServiceImpl extends ServiceImpl<MmsImportTaskMapper, MmsImportTask> implements MmsFileUpDownService {

    @Override
    public ResponseResult fileUpload(MultipartFile file) {
        if (file.isEmpty()) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        String OSName = System.getProperty("os.name");
        String filePath = OSName.toLowerCase().startsWith("win") ? FILE_DOWNLOAD_PATH
                : FILE_DOWNLOAD_PATH_LINUX;

        String fileName = file.getOriginalFilename();

        int size = Math.round(file.getSize() / 1024);
        int sizeMB = Math.round(size / 1024);
        if (sizeMB > IMG_UPLOAD_MAX) {
            return CommonResult.failed(CommonCodeEnum.FILE_SIZE_LIMIT_EXCEEDED);
        }
        if (size == IMG_UPLOAD_MIN) {
            return CommonResult.failed(CommonCodeEnum.FILE_SIZE_LIMIT_MIN);
        }
        log.debug(fileName + "-->" + size + "KB");
//        String[] fileTypeArr = fileName.split("u002E");
//        String fileType = fileTypeArr[fileTypeArr.length - 1];

        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String timeTemp = new Date().getTime() + "";

        String completePath = "";
        String newFileName = "";
        if (fileName.lastIndexOf(".") == -1) {
            completePath = filePath + timeTemp;
            newFileName = timeTemp;
        } else {
            completePath = filePath + timeTemp + "." + suffix;
            newFileName = timeTemp + "." + suffix;
        }

        File dest = new File(completePath);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
            Map<String, Object> map = new HashMap<>();
            map.put("oldFileName", fileName);
            map.put("newFileName", newFileName);
            return CommonResult.success(map);
        } catch (MaxUploadSizeExceededException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FILE_SIZE_LIMIT_EXCEEDED);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FAIL);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FAIL);
        }
    }

    @Override
    public ResponseResult fileDownload(String path, HttpServletResponse response) {
        String fileName = "";
        if (path == null || path.equals("")) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        FileInputStream fis = null; //文件输入流
        BufferedInputStream bis = null;
        OutputStream os; //输出流

        String OSName = System.getProperty("os.name");
        String filePath = OSName.toLowerCase().startsWith("win") ? FILE_DOWNLOAD_PATH
                : FILE_DOWNLOAD_PATH_LINUX;
        String completePath = filePath + path;

        File file = new File(completePath);
        if (file.getParentFile().exists()) { //判断文件父目录是否存在
            try {
                log.debug("fileName=====" + file.getName());
                response.setContentType("application/force-download");
//                response.setContentType("image/**");
                response.setCharacterEncoding("UTF-8");
                // response.setContentType("application/force-download");
                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "UTF-8"));
//                response.setHeader("Access-Control-Expose-Headers", "file-type,file-name");
                byte[] buffer = new byte[1024];

                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);

                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (FileNotFoundException e) {
                return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return CommonResult.failed(CommonCodeEnum.FAIL);
            }
            log.debug("----------file download---" + fileName);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return CommonResult.failed(CommonCodeEnum.FAIL);
            }
            return null;
        } else {
            return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
        }
    }

    @Override
    public ResponseResult moduleDownload(String path, HttpServletResponse response) {
        if (path == null || path.equals("")) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        String fileName = "";
        FileInputStream fis = null; //文件输入流
        BufferedInputStream bis = null;
        OutputStream os; //输出流

        String OSName = System.getProperty("os.name");
        String filePath = OSName.toLowerCase().startsWith("win") ? FILE_MODULE_DOWNLOAD_PATH
                : FILE_MODULE_DOWNLOAD_PATH_LINUX;
        String completePath = filePath + path + ".xlsx";

        File file = new File(completePath);
        if (file.getParentFile().exists()) { //判断文件父目录是否存在
            try {
                String moduleName;
                if (path.equals("medicine")) {
                    moduleName = "药品信息导入模板.xlsx";
                }else {
                    return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
                }
                log.debug("fileName=====" + file.getName());
//                response.setContentType("application/force-download");
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//                response.setContentType("image/**");
                response.setCharacterEncoding("UTF-8");
                // response.setContentType("application/force-download");
                response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(moduleName, "UTF-8"));
                response.setHeader("file-type", "download");
                response.setHeader("file-name", URLEncoder.encode(moduleName, "utf-8"));
                response.setHeader("Access-Control-Expose-Headers", "file-type,file-name");
                byte[] buffer = new byte[1024];

                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);

                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (FileNotFoundException e) {
                return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return CommonResult.failed(CommonCodeEnum.FAIL);
            }
            log.debug("----------file download---" + fileName);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return CommonResult.failed(CommonCodeEnum.FAIL);
            }
            return null;
        } else {
            return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
        }
    }

}
